package com.fengmi.listener;

import com.fengmi.api.goods.GoodsApi;
import com.fengmi.entity.goods.MallGoods;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@RocketMQMessageListener(consumerGroup = "fengmi-html-consumer-group"
        ,topic = "goodsToHtml",selectorExpression = "goods"
        ,consumeMode = ConsumeMode.CONCURRENTLY,messageModel = MessageModel.BROADCASTING)
public class ConsumerListener implements RocketMQListener<String> {
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;
    @Value("${page.out}")
    private String OutDir;
    @Autowired
    private GoodsApi goodsApi;
    @Override
    public void onMessage(String spuId) {
        //生成静态化页面
        try {
            Configuration configuration = freeMarkerConfig.getConfiguration();
            //1.获取模板对象
            Template template = configuration.getTemplate("introduction.ftl");
            //2.创建模型数据
            MallGoods goodsDetail = goodsApi.findGoodsDetail(spuId);
            Map data = new HashMap(){{
                put("goodsDetail",goodsDetail);
                put("specList",goodsDetail.getSpecAndOpts());
                put("skuList",goodsDetail.getSkuList());
            }};
            FileWriter fileWriter = new FileWriter(OutDir+spuId+".html");
            template.process(data,fileWriter);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


    }
}
